package com.wing.product.controller.admin;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.product.model.entity.ProcessLineTemplate;
import com.wing.product.model.entity.ProcessLineTemplateRecord;
import com.wing.product.service.ProcessLineTemplateRecordService;
import com.wing.product.service.ProcessLineTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 工艺线路-工序Controller
 *
 * @author xiayang
 */
@Validated
@Api(value = "Admin-管理", tags = "#/product/processLineTemplateRecord")
@RestController("processLineTemplateRecordController")
@RequestMapping("product/admin/processLineTemplateRecord")
@RequiredArgsConstructor
public class ProcessLineTemplateRecordController {

    private final ProcessLineTemplateRecordService processLineTemplateRecordService;


    @ApiOperation(value = "查询所有", notes = "搜索")
    @GetMapping("/list")
    public PageResult<ProcessLineTemplateRecord> list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit, Long processLineTemplateId) {
        Page<ProcessLineTemplateRecord> pg = new Page<>(page, limit);
        Map queryParam = new HashMap();
        queryParam.put("processLineTemplateId", processLineTemplateId);
        IPage<ProcessLineTemplateRecord> list = processLineTemplateRecordService.list(pg, queryParam);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "添加", notes = "添加")
    @PostMapping("/add")
    public JsonResult add(ProcessLineTemplateRecord processLineTemplateRecord) {
        //工序关联记录
        List<ProcessLineTemplateRecord> processLineTemplateRecordlist = processLineTemplateRecordService.list();

        Integer sorted = 0;
        List<ProcessLineTemplateRecord> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(processLineTemplateRecordlist)) {
            ProcessLineTemplateRecord record = processLineTemplateRecordlist.stream()
                    .filter(info -> info.getProcessLineTemplateId() != null &&
                            info.getProcessLineTemplateId().longValue() == processLineTemplateRecord.getProcessLineTemplateId() &&
                            Objects.nonNull(info.getSorted()))
                    .max(Comparator.comparing(ProcessLineTemplateRecord::getSorted, Comparator.nullsLast(Comparator.naturalOrder()))).orElse(null);
            if (ObjectUtil.isNotNull(record)) {
                sorted = record.getSorted();
            }
        }
        //获取所有的工序id
        for (Long processId : processLineTemplateRecord.getProcessIds()) {
            ProcessLineTemplateRecord result = processLineTemplateRecordlist.stream()
                    //过滤工序id+模板匹配的
                    .filter(t -> t.getProcessId().longValue() == processId && t.getProcessLineTemplateId().longValue() == processLineTemplateRecord.getProcessLineTemplateId().longValue())
                    .findFirst()
                    .orElse(null);
            //没有找到就是加
            if(result == null){
                ProcessLineTemplateRecord record = new ProcessLineTemplateRecord();
                record.setProcessLineTemplateId(processLineTemplateRecord.getProcessLineTemplateId());
                record.setProcessId(processId);
                sorted = sorted + 1;
                record.setSorted(sorted);
                list.add(record);
            }
        }
        if (processLineTemplateRecordService.saveBatch(list)) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }


    @ApiOperation(value = "修改", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(ProcessLineTemplateRecord processLineTemplateRecord) {
        if (processLineTemplateRecordService.updateById(processLineTemplateRecord)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }

    @ApiOperation(value = "修改排序", notes = "修改排序")
    @PutMapping("/updateOrder")
    public JsonResult updateOrder(Long processId, Long templateId, Integer sorted) {
        if (processLineTemplateRecordService.updateByIdsForOrder(processId,templateId,sorted)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }


    @ApiOperation(value = "删除", notes = "删除")
    @DeleteMapping("/delete")
    public JsonResult delete(Long processLineTemplateRecordId) {
        if (processLineTemplateRecordService.removeById(processLineTemplateRecordId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

}
